﻿using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using System.Drawing.Drawing2D;

namespace aucn.web.au
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageSizeHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            string imgFileName = context.Request.QueryString["u"];
            int height = Convert.ToInt16(ConfigurationManager.AppSettings["HeadingImageHeight"]);
            Bitmap newImage;
            Graphics g;
            try
            {
                Bitmap image = (Bitmap)Bitmap.FromFile(context.Server.MapPath(imgFileName));
                
                
                int newHeight = height;
                int newWidth = (int)((double)image.Width * ((double)newHeight / (double)image.Height));
                newImage = new Bitmap(newWidth, newHeight);

                using (g = Graphics.FromImage(newImage))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
                    g.DrawImage(image, 0, 0, newWidth, newHeight);
                }
                

                
            }
            catch 
            {
                newImage = new Bitmap(200, height);
                using (g = Graphics.FromImage(newImage))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.FillRectangle(Brushes.White, 0, 0, 200, height);
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    //g.DrawImage(image, 0, 0, newWidth, newHeight);
                    Font font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);
                    g.DrawString("图像未找到", font, new SolidBrush(Color.DimGray), 0, 0);
                }
            }

            newImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
